<template>
  <div class="user">
    <!-- 头部 -->
    <div>
      <a-form style="padding-top: 20px" :model="form" :hideRequiredMark="true" :label-col="labelCol">
        <a-row :gutter="20">
          <a-col :span="6" :lg="5" :md="7" :xs="20">
            <a-form-item name="nickName" label="机构ID">
              <a-input v-model:value="form.id" placeholder="请输入"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6" :lg="5" :md="6" :xs="20">
            <a-form-item name="nurseId" label="机构名称">
              <a-input v-model:value="form.organName" placeholder="请输入"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6" :lg="5" :md="7" :xs="20">
            <a-form-item name="saleValue" label="上架类型">
              <a-select ref="select" v-model:value="form.type" placeholder="请选择">
                <a-select-option v-for="item in buyCar1" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6" :lg="5" :md="7" :xs="20">
            <a-form-item name="saleValue" label="状态">
              <a-select ref="select" v-model:value="form.status" placeholder="请选择">
                <a-select-option v-for="item in buyCar2" :value="item.id" :key="item.id">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="2" :lg="2" :xs="5">
            <a-button type="primary" @click="search" class="d-a-center">搜索</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :row-selection="rowSelection"
    >
      <!-- :scroll="{ y: 540, x: 'auto' }" -->

      <template #name="{ record }">
        <template v-if="record.name">
          {{ record.name }}
        </template>
        <template v-else>
          <a-tag color="warning">未实名</a-tag>
        </template>
      </template>
      <template #status="{ record }">
        <a-tag>{{ ['审核中', '已通过', '已拒绝', '已撤销'][record.status] }}</a-tag>
        <!-- <a-switch
          v-model:checked="record.status"
          :checkedValue="1"
          :unCheckedValue="0"
          @change="changeStatus(record.status, index)"
        /> -->
      </template>
      <template #type="{ record }">
        {{ ['', '新增', '更新'][record.type] }}
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record.id)" v-has="{ a: $route, b: 2 }">查看</a-button>
      </template>
    </a-table>
    <a-divider></a-divider>

    <!-- 高级筛选抽屉 -->
    <a-drawer
      width="32%"
      :destroyOnClose="true"
      v-model:visible="visible"
      class="custom-class"
      title="高级筛选"
      placement="right"
      @close="cancel"
    >
      <a-form :label-col="labelCol" :model="advancedForm">
        <a-form-item label="地理位置">
          <a-input v-model:value="advancedForm.address" placeholder="请输入地理位置"></a-input>
        </a-form-item>
        <a-form-item label="实名认证">
          <a-select ref="select" v-model:value="advancedForm.attestStatus" style="width: 120px" placeholder="请选择实名认证状态">
            <a-select-option v-for="item in isRealNameList" :value="item.id" :key="item.id">{{ item.title }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="注册渠道">
          <a-select ref="select" v-model:value="advancedForm.registsource" style="width: 120px" placeholder="请选择注册渠道">
            <a-select-option v-for="item in registSourceList" :value="item.title" :key="item.id">{{ item.title }}</a-select-option>
          </a-select>
          <!-- <a-input
            v-model="advancedForm.registsource"
            placeholder="请输入注册渠道"
            format="YYYY-MM-DD HH:mm:ss"
          ></a-input> -->
        </a-form-item>
        <a-form-item label="注册时间">
          <a-range-picker v-model:value="value1" @change="selectTime" />
        </a-form-item>
        <a-form-item label="接单数量">
          <a-slider
            v-model:value="sliderValue"
            @change="changeOrderNumber"
            range
            :tooltipVisible="true"
            :marks="marks"
            :min="0"
            :max="999"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select ref="select" v-model:value="advancedForm.isDele" style="width: 120px" placeholder="请选择当前用户状态">
            <a-select-option v-for="item in statusList" :value="item.id" :key="item.id">{{ item.title }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <a-row style="margin-top: 50px">
        <a-col :span="4" :offset="10">
          <a-button type="primary" size="large" @click="advancedSearch">搜索</a-button>
        </a-col>
      </a-row>
    </a-drawer>
    <!-- 发送短信 -->
    <template v-if="msgVisible">
      <SendMsg
        :visible="msgVisible"
        :modalType="modalType"
        :longs="myFinalLong"
        :list="myFinalFlag ? [] : mobileList"
        :nurseDto="{ ...advancedForm, ...form }"
        :userType="myFinalType"
        @closeModal="closeMsg"
      ></SendMsg>
    </template>
  </div>
</template>
<script>
import { reactive, ref, watch, computed, defineComponent, createVNode, toRefs } from 'vue'
import * as api from '@/api/organ/index'
import { CheckOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { Modal, message } from 'ant-design-vue'
import { useRoute, useRouter, viewDepthKey } from 'vue-router'
import SendMsg from '@/views/user/components/SendMsg'
import { selectAllNurseExport } from '@/api/user/index.js'
import { deleteObjBlank } from '@/assets/js/common.js'
import xlsx from 'xlsx' //这个最新版本的会报错最好装低版本本
import { useModal } from '@/hooks'
export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
    const formRef = ref('')
    const form = reactive({})
    const data = reactive({
      loading: true,
      list: [],
      advance: false, //是否是高级搜索
      mobileList: [],
      value1: '',
      selectedAll: false,
      msgLoading: false,
      sysLoading: false,
      buyCar1: [
        {
          name: '新增',
          id: 1
        },
        {
          name: '更新',
          id: 2
        }
      ],
      buyCar2: [
        {
          name: '审核中',
          id: 0
        },
        {
          name: '已通过',
          id: 1
        },
        {
          name: '已拒绝',
          id: 2
        },
        {
          name: '已撤销',
          id: 3
        }
      ]
    })
    const msgVisible = ref(false)
    const modalType = ref(0)
    const rules = {}
    // { orderNumberBegin: 0 }
    const advancedForm = reactive({})
    const isRealNameList = reactive([
      {
        title: '已实名',
        id: 2
      },
      {
        title: '未实名',
        id: 0
      }
    ])
    const statusList = reactive([
      {
        title: '启用',
        id: 0
      },
      {
        title: '停用',
        id: 1
      }
    ])
    const registSourceList = reactive([
      {
        title: 'OPPO',
        id: 1
      },
      {
        title: 'HUAWEI',
        id: 2
      },
      {
        title: 'Xiaomi',
        id: 3
      },
      {
        title: 'vivo',
        id: 4
      },
      {
        title: 'ios',
        id: 5
      },
      {
        title: 'HONOR',
        id: 6
      },
      {
        title: 'Apple',
        id: 7
      }
    ])
    const sliderValue = ref([0, 999])
    const marks = ref({
      0: '0',
      999: {
        style: {
          color: '#f50'
        },
        label: '999'
      }
    })

    const visible = ref(false)

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0
    })

    const changeOrderNumber = e => {
      console.log(e, '范围')
      advancedForm.orderNumberBegin = e[0]
      advancedForm.orderNumberEnd = e[1]
    }
    // 查询
    const search = () => {
      console.log(form, '表单内容')
      deleteObjBlank(form)
      data.advance = false
      page.current = 1
      init()
    }
    const selectTime = (e, str) => {
      console.log(e, str, '选择时间')
      advancedForm.createdAtBegin = str[0]
      advancedForm.createdAtEnd = str[1]
    }

    const columns = [
      {
        title: '机构ID',
        dataIndex: 'id',
        className: 'table',
        align: 'center'
      },
      {
        title: '机构名称',
        dataIndex: 'name',
        className: 'table',
        align: 'center'
      },
      {
        title: '负责人',
        dataIndex: 'chargePerson',
        className: 'table',
        align: 'center'
      },
      {
        title: '联系方式',
        dataIndex: 'mobile',
        className: 'table',
        align: 'center',
        ellipsis: true
      },
      {
        title: '机构地址',
        dataIndex: 'address',
        className: 'table',
        align: 'center'
      },
      {
        title: '上线类型',
        dataIndex: 'type',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'type'
        }
      },
      {
        title: '提交时间',
        dataIndex: 'createdAt',
        className: 'table',
        align: 'center'
      },
      {
        title: '状态',
        dataIndex: 'status',
        className: 'table',
        align: 'center',
        slots: {
          customRender: 'status'
        }
      },
      {
        title: '操作',
        dataIndex: 'operation',
        className: 'table',
        align: 'center',
        fixed: 'right',
        slots: {
          customRender: 'operation'
        }
      }
    ]
    const selectList = ref([])
    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => {
        return '共' + total + '条'
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true
    }))
    const myFinalLong = computed(() => {
      return data.mobileList.length
    })
    const myFinalFlag = computed(() => {
      // 带筛选条件 true 且全选的话 就true，传过去[]
      let flag = true
      let myForm = { ...advancedForm, ...form }
      if (Object.keys(myForm).length == 0) {
        flag = false
      }
      return data.selectedAll && flag
    })
    const myFinalType = computed(() => {
      return data.selectedAll ? '3' : '1'
    })

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, '当前分页')
      page.current = pagination.current
      page.pageSize = pagination.pageSize

      // 请求列表接口
      if (data.advance) {
        // 如果是高级查询
        init(advancedForm)
      } else {
        init()
      }
    }

    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        // console.log(
        //   `selectedRowKeys: ${selectedRowKeys}`,
        //   "selectedRows: ",
        //   selectedRows
        // );
        console.log(selectedRowKeys, selectedRows, '选中的是')
        data.selectedAll = selectedRowKeys.length == page.total
        selectList.value = selectedRows
      },
      onSelect: (record, selected, selectedRows) => {
        // console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectNone: () => {
        console.log('onSelectNone-----')
      },
      onSelectInvert: selectedRows => {
        console.log(selectedRows, 'selectedRows-----')
      },
      onSelectAll: async (selected, selectedRows, changeRows) => {
        console.log(selected, 44444)
        if (selected && page.current == 1) {
          data.selectedAll = true //全选
        } else {
          data.selectedAll = false
        }
      }
    })
    const changeStatus = (e, index) => {
      console.log(e.index, '是否禁用')
      // 弹框提示？确定上下架吗
      const { closeModal } = useModal.confirm({
        title: () => '确定停用当前用户吗?',
        icon: () => createVNode(ExclamationCircleOutlined),

        class: 'test'
      })
    }
    const openDrawer = () => {
      visible.value = true
    }
    // 高级筛选
    const advancedSearch = () => {
      if (Object.keys(advancedForm).length == 0) {
        message.warning('请输入你要搜索的内容！！！')
        return
      }
      page.current = 1
      // init(deleteObjBlank(advancedForm));
      init(advancedForm)
      data.advance = true

      // visible.value = false;
    }
    // /启用
    const enableUser = () => {
      const { closeModal } = useModal.confirm({
        title: '确定启用所选用户吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        cancelText: '取消'
      })
    }
    // 停用
    const disableUser = () => {
      const { closeModal } = useModal.confirm({
        title: '确定停用所选用户吗?',
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消'
      })
    }
    // 导出客户数据
    const exportData = () => {
      if (selectList.value.length == 0) {
        message.warning('请选择你要导出的用户')
        return
      }
      const { closeModal } = useModal.confirm({
        // ${selectList.value.length}条
        title: `确认导出当前数据吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          let obj = {
            ...form,
            ...advancedForm
          }
          if (selectList.value.length < page.pageSize) {
            let nurseIds = selectList.value.map(m => {
              return Number(m.nurseId)
            })
            obj = {
              nurseIds
            }
          }
          selectAllNurseExport({ ...obj }).then(res => {
            console.log(res)
            // console.log(url);
            let link = document.createElement('a')
            //创建一个a标签
            link.style.display = 'none'
            //将a标签隐藏
            link.href = res.object
            //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
            link.setAttribute('download', '护士')
            // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
            document.body.appendChild(link)
            //将上面创建的a标签加入到body的尾部
            link.click()
            //执行a标签
            closeModal()
          })
          return

          const { export_json_to_excel } = require('../../../excel/Export2Excel')
          // 表头
          const tHeader = ['护士ID', '用户名', '手机号', '地理位置', '注册日期', '接单数量', '注册渠道', '实名认证', '状态']
          // 字段
          const fitlerVal = ['nurseId', 'name', 'mobile', 'address', 'createdAt', 'orderNumber', 'registsource', 'attestStatus', 'isDele']

          const data = selectList.value.map(v => fitlerVal.map(j => v[j]))

          export_json_to_excel(tHeader, data, '导出的数据是----')
          closeModal()
        }
      })
    }

    // 系统通知

    const closeMsg = () => {
      console.log('关闭信息')
      msgVisible.value = false
    }
    const cancel = () => {
      console.log(111111111)
    }

    // 查看
    const look = key => {
      router.push({
        path: '/orgin/all/shenheDetail',
        query: {
          id: key
        }
      })
    }

    // 处理
    const deal = (key, isEdit) => {
      router.push({
        path: '/user/nurse/nurse-detail?id=' + key,
        query: {
          id: key
        }
      })
    }
    init()
    async function init(search) {
      data.loading = true
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...form
      }
      let res = await api.selectOrganDetailTemp(obj)
      if (res.success) {
        res.object.list.map(el => (el.key = el.id))
        data.list = res.object.list
        page.total = res.object.total
      }
      data.loading = false
    }
    return {
      ...toRefs(data),
      formRef,
      form,
      rules,
      columns,
      pagination,
      myFinalType,
      myFinalFlag,
      myFinalLong,
      handleTableChange,
      search,
      deal,
      look,
      rowSelection,
      changeStatus,
      labelCol: { style: { fontWeight: 'bolder', width: '100px' } },
      exportData,
      enableUser,
      disableUser,
      visible,
      openDrawer,
      advancedForm,
      isRealNameList,
      statusList,
      advancedSearch,
      sliderValue,
      marks,
      changeOrderNumber,
      msgVisible,
      closeMsg,
      modalType,
      registSourceList,
      cancel,
      selectTime
    }
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    SendMsg
  }
}
</script>

<style scoped lang="less">
.img {
  width: 50px;
  height: 50px;
}
.title {
  font-weight: bold;
}
.search {
  background-color: #e6e6e6;
  margin-bottom: 20px;
}
</style>
